const Koa = require('koa')
const app = new Koa()
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')

const render = require('koa-art-template');
const static = require('koa-static-router');
var path = require('path');


// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())


app.use(static({
  dir: 'public',  //静态资源目录对于相对入口文件index.js的路径
  router: "/static/"   //路由命名
}))


render(app, {
  root: path.join(__dirname, 'views'),
  extname: '.art',
  debug: process.env.NODE_ENV !== 'production'
});

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
const index = require('./routes/index')
app.use(index.routes(), index.allowedMethods())

const users = require('./routes/users')
app.use(users.routes(), users.allowedMethods())

const bot = require('./routes/bot')
app.use(bot.routes(), bot.allowedMethods())


// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
